
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>  //需要的头文件

static const char *filename = "/dev/my_ds18b20";
static int num = 0;

float getTemplture(char buf[]){
    // 假设 buf[0] 是高字节，buf[1] 是低字节
    //  printf(" buf[0] = %x, buf[1] = %x\n", buf[0], buf[1]);
    unsigned short temp = (buf[0] << 8) | buf[1];
    // printf(" temp = %x\n", temp);
    float temperature;
    // 检查温度是否为负数
     if ((buf[1] & 0xF8) == 0) {
        //正数
        temperature = (temp) * 0.0625f;
        // printf(" 正数temperature = %f\n", temperature);
    }else {
        //负数
        temperature = -((~(temp) + 1) * 0.0625f);
        // printf(" 负数temperature = %f\n", temperature);
    }
    return temperature;
}
int main( int argc, char *argv[]){
    FILE *fp = fopen(filename, "r");
    while( num < 100000 ){
        num++;
        if (fp == NULL){
            printf("open file %s failed\n", filename);
            return -1;
        }
        char buf[2] = {0};
        int ret = fread(buf, 1, sizeof(buf), fp);
        if (ret < 0){
            printf("read file %s failed\n", filename);
            return -1;
        }
        // printf("read file %s success, buf[0] = %x, buf[1] = %x\n", filename, buf[0], buf[1]);
        float temp = getTemplture(buf);
        // printf("read file %s success, templture = %s\n", filename, temp);
         // 输出温度值
        printf("Temperature: %.2f°C\n", temp);
        sleep(1);
    }
    fclose(fp);
    printf("close file %s success\n", filename);
    return 0;
}